package cn.itsource.pethome.jwt;

import cn.itsource.pethome.utils.JwtUtils;
import cn.itsource.pethome.utils.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

//登录上下文，把登录的相关信息放到这里面，方便调用
// 问题1：不受spring管理的类，想要获取受spring管理的bean 只要获取到spring容器就可以从容器中获取
@Slf4j
@Component
public class LoginContextUtils {
    @Value("${jwt.rsa.pub}")
    private String jwtRsaPub;
    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;


    /**
     *
     * @param request
     * @return 如果是后台需要返回employee，如果是前台返回user
     */
    public Object getLoginUser(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token))
            return null;
        //获取公钥
        PublicKey publicKey = null;
        try {
            publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取公钥失败！");
        }
        //通过公钥解析token，登陆载荷体
        Payload<PayloadData> payload = JwtUtils.getInfoFromToken(token, publicKey, PayloadData.class);
        PayloadData payloadData = payload.getUserInfo();
        if (payloadData==null){
            log.error("payloadData is null!");
            return null;
        }
        return payloadData.getUser()!=null?payloadData.getUser():payloadData.getAdmin();
    }
}